import urllib.request
import http.cookiejar

form = {'formhash': '',
        'referer': 'https://www.bbaaz.com/',
        'loginfield': 'username',
        'username': 'xxxxx',
        'password': 'xxxxx',
        'questionid': '0',
        'answer': ''}
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3562.0 Safari/537.36'}
loginURL = "https://www.bbaaz.com/member.php?mod=logging&action=login"
query = "&loginsubmit=yes&frommessage&loginhash=xxx&inajax=1"

"""为什么刚开始就直接使用带Cookie的opener呢，经过测试，在打开登录界面的时候，服务器就会向客户端发送3个Cookie，这些Cookie同样有验证作用，如果不带上，那么登录的时候，服务器会返回，含有非法字符，无法登录"""
cookie = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cookie))

req = urllib.request.Request(loginURL, headers = headers)
resp = opener.open(req)
s = resp.read().decode('utf-8')

#获取登录界面的Hash值
s = s.split('<form method=\"post\"', 1)[1].split('name=\"formhash\" value=\"', 1)
suffix = s[0].split("loginform_", 1)[1].split("\"", 1)[0]
formhash = s[1].split("\" />", 1)[0]
query = query.replace('xxx', suffix)
form['formhash'] = formhash
post_form = urllib.parse.urlencode(form).encode('UTF-8')


req = urllib.request.Request(loginURL + query, headers = headers, data = post_form)
opener.open(req)

#你要访问的网页
req = urllib.request.Request(form['referer'], headers = headers)
resp = opener.open(req)
s = resp.read().decode('UTF-8')